/**
 * Bestpay.com.cn Inc.
 * Copyright (c) 2011-2020 All Rights Reserved.
 */
package com.suxiaoxiao.springbootlearn.designpattern.proxypattern.proxy;

import com.suxiaoxiao.springbootlearn.designpattern.proxypattern.pojo.PersonBean;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * 拦截器
 *
 * @author zhaorongzhang
 * @version InvokeMethodContant.java, v 0.1 2020/1/13 12:05 上午 zhaorongzhang Exp $$
 */
public abstract class InvokeMethodConstant implements InvocationHandler {

    final protected String METHOD_GET = "get";
    final protected String METHOD_SET = "set";
    final protected String METHOD_SET_HOT_OR_NOT_RATING = "setHotOrNotRating";

    PersonBean person;

    /**
     * 方法前缀为 get 的拦截
     * @return
     */
    protected abstract Object getMethodHandler(Method method, Object[] args) throws InvocationTargetException, IllegalAccessException;

    /**
     * 方法为 setHotOrNotRating 的拦截
     * @return
     */
    protected abstract Object setRatingMethodHandler(Method method, Object[] args) throws InvocationTargetException, IllegalAccessException;

    /**
     * 方法前缀为 set 的拦截
     * @return
     */
    protected abstract Object setMethodHandler(Method method, Object[] args) throws InvocationTargetException, IllegalAccessException;

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws IllegalAccessException {
        try {
            if (method.getName().startsWith(METHOD_GET)) {
                return getMethodHandler(method, args);
            } else if (method.getName().equals(METHOD_SET_HOT_OR_NOT_RATING)) {
                return setRatingMethodHandler(method, args);
            } else if (method.getName().startsWith(METHOD_SET)) {
                return setMethodHandler(method, args);
            }
        } catch (InvocationTargetException | IllegalAccessException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 通过
     * @param method
     * @param args
     * @return
     * @throws InvocationTargetException
     * @throws IllegalAccessException
     */
    protected Object pass(Method method, Object[] args) throws InvocationTargetException, IllegalAccessException {
        return method.invoke(person, args);
    }

    /**
     * 拦截
     * @return
     * @throws IllegalAccessException
     */
    protected Object notPass() throws IllegalAccessException {
        throw new IllegalAccessException();
    }

}